package com.jdd.pedicure.controller;

import com.jdd.pedicure.Utils.MD5Utils;
import com.jdd.pedicure.entity.Admin;
import com.jdd.pedicure.service.AdminService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpSession;
import java.io.UnsupportedEncodingException;
import java.security.NoSuchAlgorithmException;


@Controller
public class IndexController {
    @Autowired
    AdminService adminservice;

    @RequestMapping("/")
    public String goIndex() {
        return "redirect:index";
    }

    @RequestMapping("/login")
    public String login(Admin admin) {
        return "login";
    }

    @RequestMapping("/loginmethod")
    public ModelAndView loginmethod(Admin admin, ModelAndView model, HttpSession session) throws UnsupportedEncodingException, NoSuchAlgorithmException {
        String pwd = MD5Utils.EncoderByMd5(admin.getPassword());
        admin.setPassword(pwd);
        Admin login = adminservice.login(admin);
        if (login != null) {
            session.setAttribute("username", login.getUserName());
            session.setAttribute("auth", login.getAuth());
            session.setAttribute("userId", login.getUserId());
            System.out.println(session.getAttribute("auth"));
            model.setViewName("redirect:index");
            return model;
        } else
            model.addObject("error", "用户名或密码错误");
        model.setViewName("login");
        return model;
    }

    @RequestMapping("/logOut")
    public String logOut() {
        return "redirect:login";
    }

    @RequestMapping("/main")
    public String main() {
        return "main";
    }

    @RequestMapping("/index")
    public String index() {
        return "index";
    }

    public static void main(String[] args) throws UnsupportedEncodingException, NoSuchAlgorithmException {
        System.out.println(MD5Utils.EncoderByMd5("admin"));
    }
}
